/*
 * @Author: wwxin
 * @Date: 2024-04-09 13:48:54
 * @LastEditors: wwxin
 * @LastEditTime: 2024-05-06 16:48:09
 * @FilePath: /admin/src/router/axios.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from "axios";
import store from "@/store/";
import router from "@/router/router";
import { serialize } from "@/util/util";
import { getToken } from "@/util/auth";
import { Message } from "element-ui";
import website from "@/config/website";
import { Base64 } from "js-base64";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// 设置全局 baseURL
axios.defaults.baseURL = "https://api.mszcdf.cn"; // https://api.aiqishq.com process.env.NODE_ENV === "production" ? "/user/" : "/",

//默认超时时间
axios.defaults.timeout = 30000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500;
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress 配置
NProgress.configure({
  showSpinner: false,
});
//http request拦截
axios.interceptors.request.use(
  (config) => {
    // console.log("请求拦截:", config);

    //开启 progress bar
    NProgress.start();

    // // 判断请求路径，将/api替换成空
    if (config.url && config.url.startsWith("/api")) {
      config.url = config.url.replace("/api", "");
    }

    //headers判断是否需要
    const authorization = config.authorization === false;
    if (!authorization) {
      config.headers["Authorization"] = `Basic ${getToken()}`;
    }
    //让每个请求携带token
    const meta = config.meta || {};
    const isToken = meta.isToken === false;
    if (getToken() && !isToken) {
      config.headers[website.tokenHeader] = `bearer ${getToken()}`;
    }
    //headers中配置text请求

    if (config.text === true) {
      config.headers["Content-Type"] = "text/plain";
    }
    //headers中配置serialize为true开启序列化
    if (config.method === "post" && meta.isSerialize === true) {
      config.data = serialize(config.data);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// axios.interceptors.response.use(
//   (res) => {
//     NProgress.done();
//     const { data } = res;

//     // 如果返回格式是 { code, msg, data }
//     if (data && data.code !== undefined) {
//       if (data.code !== 200) {
//         Message.error(data.msg || "请求失败");
//         return Promise.reject(new Error(data.msg));
//       }
//       return data.data; // 返回 data.data（即 { total, list }）
//     }

//     // 如果直接返回 { total, list }
//     return data;
//   },
//   (error) => {
//     NProgress.done();
//     Message.error(error.message || "请求失败");
//     return Promise.reject(error);
//   }
// );

//http response 拦截
axios.interceptors.response.use(
  (res) => {
    //关闭 progress bar
    NProgress.done();
    //获取状态码

    const status = res.data.err || res.status;
    const statusWhiteList = website.statusWhiteList || [];
    const message =
      res.data.msg ||
      res.data.error_description ||
      res.data.message ||
      "未知错误";
    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res);
    //如果是401则跳转到登录页面
    if (status === 401)
      store.dispatch("FedLogOut").then(() => router.push({ path: "/login" }));
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
      Message({
        message: message,
        type: "error",
      });
      return Promise.reject(new Error(message));
    }
    return res.data;
  },
  (error) => {
    NProgress.done();
    return Promise.reject(new Error(error));
  }
);

export default axios;
